/*
 * TopBooks.fx
 * Author: Yu Min-ting
 * Created on 2009-7-13, 15:26:23
 */

package com.sjtu.fx.book;

import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.scene.input.MouseEvent;

import javafx.scene.shape.Rectangle;
import com.sjtu.fx.tools.Panel;

import javafx.scene.image.ImageView;

import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.image.Image;


import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;

import javafx.io.http.HttpRequest;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONArray;
import org.json.JSONObject;

import com.sjtu.fx.tools.SwingTextArea;

import java.lang.System;

import javafx.scene.layout.Tile;

public class TopBooks extends CustomNode {
    var panel:Panel;
     public var title:String = bind title with inverse;
    public var urls:String[] = bind urls with inverse;
    public var images:Image[] = bind images with inverse;
    var control: Integer = 0;
    var variable = 1.0;
    var tv = Timeline {
        autoReverse: true
        repeatCount:100
        keyFrames: [
            KeyFrame {
                action: function() {
                    if (control >= 5){
                        control = 0;
                    }
                    else {
                        control = control + 5;
                    }
                }
                time: 8s
                values: [
                    variable => 0.2 tween Interpolator.LINEAR
                ]
            }
            KeyFrame {
            time: 8s
            values: [
                variable => 1.0 tween Interpolator.LINEAR
            ]
        }

        ]
    }

    var top: Rectangle = Rectangle{
        width:100 height:22
        x:15 y:5
        fill:Color.rgb(200,225,230)
            onMouseEntered: function( e: MouseEvent ):Void {
                top.fill = Color.rgb(152, 190, 198)
        }
            onMouseExited: function(e:MouseEvent) {
                top.fill = Color.rgb(200,225,230)
        }
            onMouseClicked: function( e: MouseEvent ):Void {
            //to do
        }
    }
    var topText = Text {
        font: Font {size:14 name: "Verdana Bold"}
        fill: Color.rgb(11,51,60)
        content: "Top Books"
        x:15 y:20
    };
    var recent: Rectangle = Rectangle{
        width:105 height:20
        x:120 y:5
        fill:Color.rgb(200,225,230)
            onMouseEntered: function( e: MouseEvent ):Void {
                recent.fill = Color.rgb(152, 190, 198)
        }
            onMouseExited: function(e:MouseEvent) {
                recent.fill = Color.rgb(200,225,230)
        }
            onMouseClicked: function( e: MouseEvent ):Void {
            //to do
        }
    }
     var recentText = Text {
        font: Font {size:14 name: "Verdana Bold"}
        fill: Color.rgb(11,51,60)
        content: "Recent Books "
        x:120 y:20
    };

    var titleLabel = SwingTextArea{
        text: bind title
        columns:30
        rows:2
        editable:false
        visible:false
        opacity:1
    }



    override protected function create() : Node {
        tv.playFromStart();
   //     ResentBook();
        TopBook();
        images[0] = Image{url:"{__DIR__}Loading.jpg"};
        images[1] = Image{url:"{__DIR__}Loading.jpg"};
        images[2] = Image{url:"{__DIR__}Loading.jpg"};
        images[3] = Image{url:"{__DIR__}Loading.jpg"};
        images[4] = Image{url:"{__DIR__}Loading.jpg"};
        images[5] = Image{url:"{__DIR__}Loading.jpg"};
        images[6] = Image{url:"{__DIR__}Loading.jpg"};
        images[7] = Image{url:"{__DIR__}Loading.jpg"};
        images[8] = Image{url:"{__DIR__}Loading.jpg"};
        images[9] = Image{url:"{__DIR__}Loading.jpg"};
        Group{
            content:[
                 panel = Panel {
                    width:    465
                    height:   240
                    title:    "Top Books | Recent Books"
                    translateX: 0
                    translateY: 0
                },
                top, topText,
                recent, recentText,
                titleLabel,
               Tile{
                    translateX:21 translateY:75
                    hgap:6
                    columns:5
                    tileWidth:80
         //           width:425
                    nodeHPos: HPos.CENTER
                    content:
                        for (i in[0..4]){
                            ImageView {
                               cursor: Cursor.HAND
                               opacity: bind variable
                                image: bind images[i+control] 
                   //             {
                   //                 url: {urls[i+control]}
                  //              }
                              onMouseEntered: function( e: MouseEvent ):Void {
                                    title = urls[i+control];
                                    titleLabel.visible = true;
                                    titleLabel.opacity = 1;
                                    titleLabel.translateX = 21+ i*18;
                                    titleLabel.translateY = 185;
                              }
                              onMouseExited: function( e: MouseEvent ):Void {
                                    titleLabel.visible = false;
                              }
                              onMouseClicked: function( e: MouseEvent ):Void {
                                    
                                }


                            }


                        }


                }



            ]
        }
     }

    function ResentBook(){
             HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/ResentBook"

       onOutput: function(os:OutputStream) {
            try {
                var temp:String = "obj=1";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }

        onInput: function(is: InputStream) {
            try {
//              System.out.println("Here");
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                json = new JSONObject(result);
                var bookNamelist:JSONArray = json.getJSONArray("bookNameList");
                var authorlist:JSONArray = json.getJSONArray("authorList");
                var publisherList:JSONArray = json.getJSONArray("publisherList");
                var urlList:JSONArray = json.getJSONArray("urlList");
                var idList:JSONArray = json.getJSONArray("idList");
                var scoreList:JSONArray = json.getJSONArray("scoreList");
                var index:Integer = 0;
       //         searchResult = SearchResults{id:"searchResult"  translateX:225 translateY:135  visible:false}
                while(index<bookNamelist.length()){
                    System.out.println("{__DIR__}{urlList.get(index).toString()}");
                    urls[index] = urlList.get(index).toString();
                    images[index] = Image{url:"{__DIR__}{urlList.get(index).toString()}"};

                    index++;
                }
                }
             finally {
              //   this.parent.lookup("topBooks").visible = true;
             //    this.parent.lookup("recommendBooks").visible = false;
              //   this.parent.lookup("searchResult").visible = false;
                is.close();
            }
        }
    }.start();

     }


function TopBook(){
             HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/TopBook"

       onOutput: function(os:OutputStream) {
            try {
                var temp:String = "obj=1";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }

        onInput: function(is: InputStream) {
            for (i in[1..6]){
                (this.parent.lookup("searchResult") as SearchResults).Images.content[0] = null;
            }
            try {
//              System.out.println("Here");
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                json = new JSONObject(result);
                var bookNamelist:JSONArray = json.getJSONArray("bookNameList");
                var authorlist:JSONArray = json.getJSONArray("authorList");
                var publisherList:JSONArray = json.getJSONArray("publisherList");
                var urlList:JSONArray = json.getJSONArray("urlList");
                var idList:JSONArray = json.getJSONArray("idList");
                var scoreList:JSONArray = json.getJSONArray("scoreList");
                var index:Integer = 0;
       //         searchResult = SearchResults{id:"searchResult"  translateX:225 translateY:135  visible:false}
                while(index<bookNamelist.length()){
                    System.out.println("{__DIR__}{urlList.get(index).toString()}");
         //           urls[index+5] = urlList.get(index).toString();
                    images[index] = Image{url:"{__DIR__}{urlList.get(index).toString()}.jpg"};
       /*             System.out.println(bookNamelist.get(index));
                    System.out.println(authorlist.get(index));
                    System.out.println(publisherList.get(index));
                    System.out.println(urlList.get(index));
                    System.out.println(idList.get(index));
                    var book:Results = Results{
                        id:idList.get(index).toString(),
                        url:urlList.get(index).toString(),
                        publisher: publisherList.get(index).toString(),
                        author: authorlist.get(index).toString(),
                        title:bookNamelist.get(index).toString(),
                        score:scoreList.get(index).toString()
                    };
                //    (this.parent.lookup("searchResult") as SearchResults).results[index] = book;
                    (this.parent.lookup("searchResult") as SearchResults).url[index]
                            =  urlList.get(index).toString() ;
                    (this.parent.lookup("searchResult") as SearchResults).author[index]
                            = authorlist.get(index).toString();
                    (this.parent.lookup("searchResult") as SearchResults).publisher[index]
                            = publisherList.get(index).toString();
                    (this.parent.lookup("searchResult") as SearchResults).title[index]
                            = bookNamelist.get(index).toString();
                    (this.parent.lookup("searchResult") as SearchResults).bookid[index]
                            = idList.get(index).toString();
    /*                if(index<5){
                    var box:Group = Group{
                        id: index.toString()
                        content: [
                            HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                   //         System.out.println("###Here###{bookNamelist.}");
                                            var i:Integer = Integer.parseInt(idList.get(Integer.parseInt(box.id)).toString());
                                            System.out.println(i);
                                            var boxid:Integer = Integer.parseInt(idList.get(Integer.parseInt(box.id)).toString());
                                            setBorrowBookPage(boxid,bookNamelist.get(Integer.parseInt(box.id)).toString(),authorlist.get(Integer.parseInt(box.id)).toString(),
                                                    publisherList.get(Integer.parseInt(box.id)).toString(),urlList.get(Integer.parseInt(box.id)).toString());
                                        }
                                        image: Image{url: urlList.get(index).toString() }
                                    }
                                ]
                             }]};
                             (this.parent.lookup("searchResult") as SearchResults).Images.content[index+1] = box;
                       }
                      // System.out.println("{index}:{bookNamelist.get(index)}");
          */             index++;
                }
                }
             finally {
              //   this.parent.lookup("topBooks").visible = true;
             //    this.parent.lookup("recommendBooks").visible = false;
              //   this.parent.lookup("searchResult").visible = false;
                is.close();
            }
        }
    }.start();

     }
}
